package admin

import (
	"fmt"
	"new_club_recruitment/global"
	"new_club_recruitment/model/admin"
	"new_club_recruitment/model/admin/request"
	common "new_club_recruitment/model/common/request"
	"new_club_recruitment/service/system"
	"new_club_recruitment/utils"
	"strconv"
)

type AdminService struct{}

//GetAdminInfoList 获取所有的管理员
func (a *AdminService) GetAdminInfoList(info request.AdminSearch) (list interface{}, total int64, err error) {
	var admins []admin.SysAdmin
	db := global.GVA_DB
	if info.Name != "" {
		db = db.Where(fmt.Sprintf("admin_name like '%%%s%%'", info.Name))
	}
	err = db.Model(admin.SysAdmin{}).Count(&total).Error
	if err != nil {
		return
	}
	err = db.Limit(info.PageSize).Offset(info.PageSize * (info.PageNum - 1)).Find(&admins).Error
	return admins, total, err
}

//GetAdminInfo 获取单一给管理员信息
func (a *AdminService) GetAdminInfo(id string) (data admin.SysAdmin, err error) {
	db := global.GVA_DB
	err = db.Where("id = ?", id).First(&data).Error
	return
}

// AddAdminInfo 添加管理员信息
func (a *AdminService) AddAdminInfo(info admin.SysAdmin) (err error) {
	db := global.GVA_DB
	//info.Password = utils.BcryptHash(info.Password)
	err = db.Create(&info).Error
	return err
}

// DelAdminInfo 删除管理员信息
func (a *AdminService) DelAdminInfo(id string) (err error) {
	db := global.GVA_DB
	err = db.Where("id = ?", id).Delete(&admin.SysAdmin{}).Error
	return err
}

// UpdateAdminInfo 修改管理员信息
func (a *AdminService) UpdateAdminInfo(info admin.SysAdmin) (err error) {
	db := global.GVA_DB
	err = db.Updates(&info).Error
	return err
}

// Login 登陆
func (a *AdminService) Login(info common.Info) (data admin.SysAdmin, url []common.CasbinInfo, err error) {
	var r system.RedisServe
	var casbinPath system.CasbinService
	var token string
	db := global.GVA_DB
	err = db.Where("admin_name = ?", info.Name).First(&data).Error
	if err != nil {
		return
	}
	if err = utils.BcryptCheck(info.Password, data.Password); err != nil {
		return
	}
	token, err = utils.GenToken(&data)
	if err != nil {
		return
	}
	err = r.Puttoken(strconv.Itoa(int(data.ID)), token)
	if err != nil {
		return
	}
	url = casbinPath.GetPolicyPathByAuthorityId(data.Permission)
	data.Token = token
	return

}
